import { Flex, Layout, message, Spin } from 'antd';
import { useState, useEffect, useMemo } from 'react';
import useWindowWidth from '@/hooks/event/use-window-width';
import {
  // useChatPage,
  // useConfig,
  // useConfigActions,
  // useHotIssueList,
  useInitializeData,
  // useAppInfo,
} from '@/store/configStore';
import MessageSendInputHome from './components/MessageSendInputHome';
import { SvgIcon } from '@/components/icon';
import './style/homepage.css';

import { hotIssues } from '@/common/types';

import FunasrRecorder from '@/pages/app-qa/components/chat/components/FunasrRecorder';

import LicenseModal from '@/pages/components/modal/LicenseConfirm';
import { useOrchestrationStore, HotQuestion } from '@/store/orchestrationStore';

const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;
import orchestrationService from '@/api/services/orchestrationService';
import { ChatBoxVariableInput } from '@/components/chat-box/VariableInputItem';
import { VariableInputEnum } from '@/types/workflow/constant';
import AppImageDisplay from './components/AppImageDisplay';
import { AppType } from '@/common/app/constants';
import { fetchConfigStatus } from '@/utils/common';
import { useParams } from '@/router/hooks';

interface HomepageProps {
  onChatStart?: (message: string) => void;
  workflowDebug?: boolean;
}

export default function PermissionPage({ onChatStart, workflowDebug = false }: HomepageProps) {
  const initializeData = useInitializeData();
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);

  const { sceneImage, appLogo } = useOrchestrationStore();
  const [isLoading, setIsLoading] = useState(false);

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const {
    workflow,
    configurations,
    hotQuestions,
    userSelectVariables,
    subAppDetail,
    isInOrchestrationPage,
    appDetail,
  } = useOrchestrationStore();

  // wokflow
  // const { appDetail } = useContextSelector(AppContext, (v) => v);
  const [chatStart, setChatStart] = useState(false);

  const userInputVariables = useMemo(() => {
    if (subAppDetail?.variables || subAppDetail?.workflow?.chatConfig?.variables) {
      const subAppVariables =
        subAppDetail?.variables?.length > 0
          ? subAppDetail?.variables
          : subAppDetail?.workflow?.chatConfig?.variables;
      const subAppVariablesFliter = subAppVariables?.filter(
        (item: any) => item?.type !== VariableInputEnum.custom,
      );
      return subAppVariablesFliter || userSelectVariables;
    }
    return (
      workflow?.chatConfig?.variables?.filter((item) => item.type !== VariableInputEnum.custom) ||
      userSelectVariables
    );
  }, [workflow, userSelectVariables, subAppDetail]);

  useEffect(() => {
    console.log('userInputVariables', userInputVariables);
  }, [userInputVariables]);

  const chatStarted =
    chatStart || userInputVariables?.length === 0 || userInputVariables?.length === undefined;

  // const isHotIssuesOpen = useMemo(() => fetchConfigStatus(configurations, 'hot_issues'), [configurations]);

  const isHotIssuesOpen = useMemo(() => {
    const isEnable = fetchConfigStatus(configurations, 'hot_issues');
    const isSubEnable = fetchConfigStatus(subAppDetail?.configurations, 'hot_issues');
    return subAppDetail ? isSubEnable : isEnable;
  }, [configurations, subAppDetail]);

  const startFlowChat = (value: boolean) => {
    setChatStart(value);
    // if (value) {
    //   onChatStart && onChatStart(undefined);
    // }
  };
  // workflow end

  const isConfigAvailable = configurations.length != 0;

  const sceneImageConfig =
    (configurations.find((config) => config.name === 'scene_image')?.default_value as string) ||
    sceneImage;
  const openingRemarks = workflow
    ? workflow.chatConfig.welcomeText
    : (configurations.find((config) => config.name === 'opening_remarks')
        ?.default_value as string) || '';

  const { isPc } = useWindowWidth();

  const hotImages = [
    { icon: 'hot-book', color: '#CE33E6' },
    { icon: 'hot-case', color: '#6C82FF' },
    { icon: 'hot-fire', color: '#C966FF' },
    { icon: 'hot-note', color: '#946BF1' },
    { icon: 'hot-school', color: '#6B53FF' },
  ];

  const getRandomHotImage = (index: number) => {
    const randomIndex = index % hotImages.length;
    return (
      <SvgIcon
        icon={hotImages[randomIndex].icon}
        size={25}
        color={hotImages[randomIndex].color}
        style={{
          padding: '3px',
          marginRight: '6px',
          backgroundColor: '#E5E7ED',
          borderRadius: '8px',
          flexShrink: 0,
        }}
      />
    );
  };

  // 修改类型定义，使用联合类型来支持两种不同的对象结构
  const [hotTitle, setHotTitle] = useState<(hotIssues | HotQuestion | { content: string })[]>([]);

  const handleSend = () => {};
  const changeInputType = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    setVoice(!voice);
  };
  const handleInterrupt = () => {};
  const onSTT = (status: number) => {
    if (status == 0) {
      setIsMessageSend(true);
    }
    if (status == 1) {
      setIsMessageSend(true);
    }
    if (status == 2) {
      setIsMessageSend(false);
    }
  };
  const onVoiceStop = (inputValue: string) => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    if (inputValue && onChatStart) {
      onChatStart(inputValue);
    }
  };
  const onInterrupt = () => {
    setIsMessageSend(false);
  };
  const [voice, setVoice] = useState(false);

  const [isMessageSend, setIsMessageSend] = useState(false);

  useEffect(() => {
    fetchAppInfo();

    setTimeout(() => {
      !isPc && checkTextOverflow();
    }, 500);
  }, []);

  const { appId = '' } = useParams() as { appId: string };

  // const fetchAppInfo = async () => {
  //   const searchParams = new URLSearchParams(location.search);
  //   const id = searchParams.get('id') || searchParams.get('appId') || '';
  //   // const responseApp = await appService.brandingDetail(id, 'app');
  //   const responseApp = await orchestrationService.getAppHotIssue(id);
  //   // setAppInfoInitialize(responseApp)
  //   // 将API返回的数据转换为组件需要的格式
  //   setHotTitle(responseApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
  //   // setHotQuestions(responseApp?.hot_issues || []);
  //   setIsLoading(true);
  // };

  // useEffect(() => {
  //   if (hotQuestions && hotQuestions.length > 0) {
  //     setHotTitle(hotQuestions.map((item) => ({ content: item.content })));
  //   } else {
  //     fetchAppInfo();
  //   }
  // }, [hotQuestions]);

  // const fetchAppInfo = async () => {
  //   const responseApp = await orchestrationService.getAppHotIssue(id);
  //   setHotTitle(responseApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
  // };

  const fetchAppInfo = async () => {
    if (subAppDetail?.app_id) {
      const responseSubApp = await orchestrationService.getAppHotIssue(subAppDetail?.app_id);
      setHotTitle(responseSubApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
      setIsLoading(true);
      return;
    }
    if (!appId) {
      setHotTitle([]);
      setIsLoading(true);
      return;
    }
    if (hotQuestions && hotQuestions.length > 0) {
      setHotTitle(hotQuestions.map((item) => ({ content: item.content })));
    } else {
      const responseApp = await orchestrationService.getAppHotIssue(appId);
      setHotTitle(responseApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
    }
    setIsLoading(true);
  };

  useEffect(() => {
    fetchAppInfo();
  }, [appId, configurations, subAppDetail, hotQuestions]);

  const checkTextOverflow = () => {
    const scrollTextElements = document.querySelectorAll('.scrolltext');
    console.log(scrollTextElements);

    scrollTextElements.forEach((element) => {
      const spanElement = element.querySelector('span');
      if (!spanElement) return;

      const elementWidth = element.clientWidth || 0;
      const spanWidth = spanElement.clientWidth || 0;

      console.log(spanWidth, elementWidth, spanWidth / elementWidth);

      if (spanWidth > elementWidth) {
        const translateXValue = `${(1 - spanWidth / elementWidth) * 100}%`;
        console.log(translateXValue);

        // 如果文本超出容器，则添加动画类
        spanElement.classList.add('animate');
        spanElement.style.setProperty('--translateXValue', translateXValue);
      } else {
        // 如果文本没有超出容器，则移除动画类
        spanElement.classList.remove('animate');
      }
    });
  };

  const { voiceEnabled } = useOrchestrationStore();

  useEffect(() => {
    if (!voiceEnabled && voice) {
      setVoice(false);
    }
  }, [voiceEnabled]);

  return (
    <>
      <Layout
        className="homepage-layout h-full [-ms-overflow-style:none] [scrollbar-width:none]"
        style={{
          background: 'rgb(236,239,247)',
          height: `calc(100svh - ${workflowDebug ? '260' : isPc ? '150' : '110'}px)`,
        }}
      >
        {isLoading ? (
          <div
            className="mt-24 flex flex-col  items-center self-center"
            style={{
              width: isPc ? '800px' : '100%',
              margin: 'auto',
              // paddingBottom: isPc ? '100px' : '50px',
              paddingTop: isPc ? 'unset' : '60px',
            }}
          >
            {(workflow || isConfigAvailable) && (
              // && sceneImageConfig
              <AppImageDisplay
                sceneImageConfig={sceneImageConfig}
                appLogo={appLogo}
                workflow={workflow}
                chatStarted={chatStarted}
              />
            )}

            <div className="mb-10 mt-4 px-5 text-[14px] font-normal text-[#1D2129] outline-none">
              {openingRemarks}
            </div>

            <div>
              {!chatStarted && (
                <ChatBoxVariableInput chatStart={chatStarted} setChatStart={setChatStart} />
              )}
            </div>

            {(workflow || isConfigAvailable) &&
              (chatStarted || appDetail?.appType == AppType.fusion) && (
                <div className={`${!isPc ? 'w-full px-2' : ''}`}>
                  <div
                    className="jr-step-1 flex items-center border-none py-4"
                    style={
                      !isPc
                        ? {
                            width: '100%',
                          }
                        : {}
                    }
                  >
                    <div
                      className={`relative flex rounded-[12px] p-2 ${
                        isPc ? 'w-[800px]' : 'w-full'
                      }`}
                      style={{
                        background: `linear-gradient(0deg, rgba(200, 232, 255, 0.096) 0%, rgba(200, 232, 255, 0.48) 116.99%),
                                linear-gradient(73.98deg, rgba(113, 242, 219, 0) 76.04%, rgba(113, 242, 219, 0.2) 108.48%),
                                linear-gradient(317.33deg, rgba(18, 118, 255, 0) 82.47%, rgba(18, 118, 255, 0.4) 145.92%)`,
                      }}
                    >
                      {voice == true ? (
                        <FunasrRecorder
                          isMessageSend={isMessageSend}
                          onInterrupt={onInterrupt}
                          onStop={onVoiceStop}
                          onSTT={onSTT}
                          onSwitch={changeInputType}
                          className="flex h-full w-full items-center justify-center"
                        />
                      ) : (
                        <MessageSendInputHome
                          handleSend={handleSend}
                          changeInputType={changeInputType}
                          handleInterrupt={handleInterrupt}
                          isMessageSend={isMessageSend}
                          isHome={true}
                          setChatStart={
                            appDetail?.appType == AppType.fusion ? setChatStart : undefined
                          }
                          onChatStart={(msg) => {
                            if (!chatStarted) {
                              message.warning('基础信息未提交！');
                              return;
                            }
                            onChatStart && onChatStart(msg);
                          }}
                        ></MessageSendInputHome>
                      )}
                    </div>
                  </div>

                  {(isHotIssuesOpen || workflow?.chatConfig.hotQuestionConfig?.open) && (
                    <div
                      className="flex flex-wrap justify-center gap-x-6"
                      style={{ width: isPc ? '800px' : '100%' }}
                    >
                      {hotTitle?.slice(0, 5).map((item, index) => {
                        return (
                          <div
                            className="hot-card"
                            key={index}
                            style={{
                              fontSize: '14px',
                              color: 'black',
                              height: '40px',
                              background: '#F9FBFF',
                              display: 'flex',
                              alignItems: 'center',
                              padding: '0 8px',
                              marginTop: '10px',
                              cursor: 'pointer',
                              width: isPc ? 'unset' : '100%',
                            }}
                            onClick={() => {
                              if (licenseFlag && !initializeData?.is_license_valid) {
                                handleActivateClick();
                                return;
                              }
                              if (onChatStart) {
                                if (!chatStarted) {
                                  message.warning('基础信息未提交！');
                                  return;
                                }
                                onChatStart(item.content);
                              }
                            }}
                          >
                            <div>{getRandomHotImage(index)}</div>
                            <div className="scrolltext">
                              <span>{item.content}</span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              )}
          </div>
        ) : (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        )}
      </Layout>
      <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
    </>
  );
}
